package com.gykfbxxh.imovie.view.set;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.android.volley.VolleyError;
import com.app.utils.util.LogUtils;
import com.app.utils.util.ToastUtils;
import com.google.gson.reflect.TypeToken;
import com.gykfbxxh.imovie.AppApplication;
import com.gykfbxxh.imovie.R;
import com.gykfbxxh.imovie.adapter.FilmsAdapter;
import com.gykfbxxh.imovie.base.BaseActivity;
import com.gykfbxxh.imovie.bean.film.FilmEntity;
import com.gykfbxxh.imovie.bean.film.FilmList;
import com.gykfbxxh.imovie.bean.news.SearchHotList;
import com.gykfbxxh.imovie.config.TypeConstant;
import com.gykfbxxh.imovie.config.URIContant;
import com.gykfbxxh.imovie.custom.view.LabelsView;
import com.gykfbxxh.imovie.greendao.GDManager;
import com.gykfbxxh.imovie.greendao.bean.SearchHistoryGD;
import com.gykfbxxh.imovie.greendao.gen.SearchHistoryGDDao;
import com.gykfbxxh.imovie.listener.HttpListener;
import com.gykfbxxh.imovie.utils.DialogUtils;
import com.gykfbxxh.imovie.utils.HttpUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 搜索新闻页面
 * @author xuxinghai
 *
 */
public class SearchActivity extends BaseActivity implements OnClickListener, AbsListView.OnScrollListener {
	
	/********** 页面控件 **************/
	private LabelsView labels;
	TextView serarchView;//搜索按钮
	private EditText editText;//搜索编辑框
	private ListView listView;//搜索结果
	private LinearLayout hotLayout;//热词模块
	private View ll_historyhide;//历史记录多余部分
	private ListView history_listView;//历史记录
	private LinearLayout ll_historyListView;//历史记录模块
	private ProgressDialog progressDialog;

	/************ 逻辑数据 ***********/
	private FilmsAdapter searchListAdapter;
	private List<FilmEntity> list;
	private List<String> historyList = new ArrayList<>();

	private boolean isRefreshing;//是否正在刷新
	private int page = 1;

	private MyBaseAdapter mAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search);
		//初始化页面
		initView();
		//加载热词
		loadHotData();
		//关闭键盘
		toggleSoftInput();
	}

	/**
	 * 初始化页面
	 */
	private void initView(){
		labels = (LabelsView)findViewById(R.id.labels);
		labels.setSelectType(LabelsView.SelectType.NONE);
		labels.setOnLabelClickListener(new LabelsView.OnLabelClickListener() {
			@Override
			public void onLabelClick(View label, String labelText, int position) {
				toggleSoftInput();
				searchData(labelText, true);
			}
		});
		hotLayout = (LinearLayout) findViewById(R.id.hotLayout);
		editText = (EditText) findViewById(R.id.editText_search);
		listView = (ListView) findViewById(R.id.listView_search);
		history_listView = (ListView) findViewById(R.id.history_listView);
		ll_historyListView = (LinearLayout)findViewById(R.id.ll_historyListView);
		ll_historyhide = findViewById(R.id.ll_historyhide);
		serarchView = (TextView) findViewById(R.id.imageView_search);
		serarchView.setOnClickListener(this);
		findViewById(R.id.iv_search).setOnClickListener(this);
		findViewById(R.id.iv_del).setOnClickListener(this);
		findViewById(R.id.tv_clear).setOnClickListener(this);

		listView.setOnScrollListener(this);
		// 配置mListView
		//搜索新闻适配
		list=new ArrayList<FilmEntity>();
		//所有样式全部以新闻资讯的为准
		searchListAdapter = new FilmsAdapter(list, this, TypeConstant.CHANNEL_TYPE_NEWS);
		listView.setAdapter(searchListAdapter);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if(list!=null&&!list.isEmpty()){
					FilmEntity news = list.get(position);
					if (news == null) {
						return;
					}
					ToastUtils.makeText("点击了"+news.getFName());
				}
			}
		});

		//配置搜索编辑框
		editText.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				toggleSoftInput();
				String searchText = editText.getText().toString().trim();
				searchData(searchText,true);
				return true;
			}
		});
		editText.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (0 < hastableData("")) {
					ll_historyListView.setVisibility(View.VISIBLE);
					hotLayout.setVisibility(View.GONE);
					listView.setVisibility(View.GONE);
					queryData(editText.getText().toString());
				}
			}
		});

		editText.addTextChangedListener(new TextWatcher() {
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				if (editText == null) {
					return;
				}
				String tempName = editText.getText().toString();
				if (TextUtils.isEmpty(tempName)) {
					serarchView.setEnabled(false);
				} else {
					serarchView.setEnabled(true);
				}
				listView.setVisibility(View.GONE);
				if (hasData(tempName)) {
					ll_historyListView.setVisibility(View.VISIBLE);
					hotLayout.setVisibility(View.GONE);
				} else {
					ll_historyListView.setVisibility(View.GONE);
					hotLayout.setVisibility(View.VISIBLE);
				}
				//只允许输入 汉字 字母 数字
				String   regEx  =  "[^a-zA-Z0-9\u4E00-\u9FA5]";
				Pattern p   =   Pattern.compile(regEx);
				Matcher m   =   p.matcher(tempName);
				tempName =  m.replaceAll("").trim();
				// 根据tempName去模糊查询数据库中有没有数据
				queryData(tempName);

			}
		});

		ll_historyhide.setOnClickListener(this);
		history_listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				TextView textView = (TextView) view.findViewById(R.id.it_textview);
				String name = textView.getText().toString();
				editText.setText(name);
				editText.setSelection(editText.getText().length());
			}
		});

	}

	/**
	 * 初始化等待提示弹窗
	 */
	private void initDialog(){
		if(progressDialog==null){
			progressDialog=new ProgressDialog(this);
			progressDialog.setTitle("正在搜索");
			progressDialog.setMessage("请稍候...");
		}
		try {
			if(progressDialog != null && !isFinishing()){
                progressDialog.show();
            }
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 下载热点内容
	 */
	private void loadHotData(){
		HttpListener<SearchHotList> httpListener = new HttpListener<SearchHotList>() {

			@Override
			public void onStart() {

			}

			@Override
			public void onError(VolleyError error) {
				LogUtils.e("xuxh","loadHotData.error");
			}

			@Override
			public void onSuccess(SearchHotList response) {
				if(response!=null&&response.getResult()!=null&&response.getResult().size()>0) {
					List<SearchHotList.SearchHot> strList = response.getResult();
					ArrayList<String> label = new ArrayList<>();
					for(int i=0;i<strList.size();i++){
						label.add(strList.get(i).getFKeyword());
					}
					labels.setLabels(label);
					//搜索热词适配
				}
			}
		};
		addGetRequest(URIContant.FILM_SEARCH_HOT, new TypeToken<SearchHotList>() {
		}.getType(), httpListener);

	}

	/**
	 * 下载搜素内容
	 */
	private void searchData(String search, final boolean isRefresh){
		//如果是新的搜索则记录搜索记录
		if(isRefresh){
			// 按完搜索键后将当前查询的关键字保存起来,如果该关键字已经存在就不执行保存
			boolean hasData = hasData(search);
			if (!hasData) {
				if(!TextUtils.isEmpty(search)) {
					insertData(search);
				}
			}
//
//			ll_historyListView.setVisibility(View.GONE);
			editText.setText(search);
			editText.setSelection(editText.getText().length());
			page = 1;
		}

		HttpUtils.addGetRequest(URIContant.GETFILMLIST+"&pno="+page, new TypeToken<FilmList>() {
		}.getType(), mPageName, new HttpListener<FilmList>() {

			@Override
			public void onStart() {
				isRefreshing = true;
				if(isRefresh){
					DialogUtils.getInstance().showProgressDialog(SearchActivity.this, "正在搜索中");
				}
			}

			@Override
			public void onError(VolleyError error) {
				isRefreshing = false;
//				ToastUtils.showText("无网络--"+error.getMessage());
				ToastUtils.makeText(AppApplication.getInstance().getResources().getString(R.string.neterror));
				if(isRefresh){
					if(progressDialog != null && !isFinishing()){
						progressDialog.dismiss();
					}else{
						progressDialog = null;
					}
					DialogUtils.getInstance().dismissProgressDialog();
					hintView();
				}
				if(list == null|| list == null || list.isEmpty()) 	hintView();
			}

			@Override
			public void onSuccess(FilmList response) {
				isRefreshing = false;
				if(response!=null&&response.getResult()!=null&&response.getResult().getList()!=null&&response.getResult().getList().size()>0) {
					List<FilmEntity> lists = response.getResult().getList();
					if(isRefresh){
						list.clear();
						showView();
					}
					list.addAll(lists);
					searchListAdapter.notifyDataSetChanged();
				}else {
					if(isRefresh){
						ToastUtils.makeText("未搜索到对应内容");
					}
				}
				if(isRefresh){
					DialogUtils.getInstance().dismissProgressDialog();
				}
			}
		});

		addSearchWord(search);

	}

	private void addSearchWord(String search) {
		HashMap<String,String> parms = new HashMap<>();
		parms.put("keyword",search);
		HttpUtils.addPostResultRequest(URIContant.SEARCH_ADD,mPageName,parms,null);
	}

	/**
	 * 隐藏搜素布局
	 */
	private void hintView(){
		hotLayout.setVisibility(View.VISIBLE);
		labels.setVisibility(View.VISIBLE);
		ll_historyListView.setVisibility(View.GONE);
		listView.setVisibility(View.GONE);
	}
	/**
	 * 显示搜素的布局
	 */
	private void showView(){
		if(hotLayout.getVisibility() != View.GONE){
			hotLayout.setVisibility(View.GONE);
		}
//		gridView.setVisibility(View.GONE);
		if(ll_historyListView.getVisibility() != View.GONE){
			ll_historyListView.setVisibility(View.GONE);
		}
		if(listView.getVisibility() != View.VISIBLE){
			listView.setVisibility(View.VISIBLE);
		}
	}
	/**
	 * 点击事件
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.imageView_search://搜索
			case R.id.iv_search:
				if(listView != null && listView.getVisibility() == View.VISIBLE){
					//如果当前搜索列表已经显示 则不再隐藏
					searchData(editText.getText().toString().trim(),true);
				}else{
					toggleSoftInput();
					searchData(editText.getText().toString().trim(),true);
				}
				break;
			case R.id.iv_del://清空
				clearSearch();
				break;
			case R.id.tv_clear://清空搜索历史
				clearHistory();
				break;
			case R.id.ll_historyhide://隐藏搜索历史
				hideHistoryList();
				break;

			default:

				break;
		}
	}

	/**
	 * 隐藏历史记录
	 */
	private void hideHistoryList(){
		if(ll_historyListView != null){
			ll_historyListView.setVisibility(View.GONE);
		}
		if(hotLayout != null){
			hotLayout.setVisibility(View.VISIBLE);
		}
		toggleSoftInput();
	}

	/**
	 * 清除历史纪录
	 */
	private void clearHistory(){
		deleteData();
		queryData("");
		ll_historyListView.setVisibility(View.GONE);
		hotLayout.setVisibility(View.VISIBLE);
		toggleSoftInput();
	}

	/**
	 * 清空搜索
	 */
	private void clearSearch(){
		if(editText != null){
			editText.setText("");
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
//			if(listView.getVisibility()==View.VISIBLE){
//				hintView();
//				return true;
//			}


			if(list!=null && listView.getVisibility()== View.GONE && list.size()>0) {

				listView.setVisibility(View.VISIBLE);
				ll_historyListView.setVisibility(View.GONE);
				hotLayout.setVisibility(View.GONE);

				return true;
			}

			break;

		default:
			break;
		}
		return super.onKeyDown(keyCode, event);
	}
	/**
	 * 隐藏输入法
	 */
	private void toggleSoftInput(){
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
	}
	
	@Override
	protected void onDestroy() {
		toggleSoftInput();
		super.onDestroy();
	}

	/**
	 * 插入数据
	 */
	public void insertData(String tempName) {
		if(TextUtils.isEmpty(tempName)){
			return;
		}
		long lTime = System.currentTimeMillis();
		SearchHistoryGD searchHistoryGD = new SearchHistoryGD(lTime,tempName);
		try {
			GDManager.getInstance().getSession().getSearchHistoryGDDao().insertOrReplace(searchHistoryGD);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 模糊查询数据设置只显示五条
	 */
	public  void queryData(String tempName) {
		if(TextUtils.isEmpty(tempName)) {
		    return;
		}


		try {
			List<SearchHistoryGD> list = GDManager.getInstance().getSession().getSearchHistoryGDDao()
					.queryBuilder().where(SearchHistoryGDDao.Properties.SearchStr.like("%" + tempName + "%"))
					.orderDesc(SearchHistoryGDDao.Properties.Id)
					.list();

			int count = list.size() ;
			if(count>5) {
                int counts = count-6 ;//select * from users order by id limit 10 offset 0

				List<SearchHistoryGD> list1 = GDManager.getInstance().getSession().getSearchHistoryGDDao()
						.queryBuilder()
						.where(SearchHistoryGDDao.Properties.SearchStr.like("%" + tempName + "%"))
						.orderDesc(SearchHistoryGDDao.Properties.Id)
						.limit(5)
						.offset(counts)
						.list();

                historyList.clear();
				for (int i =0;i<list1.size();i++){
					historyList.add(list1.get(i).getSearchStr());
				}
                if(mAdapter == null){
                    mAdapter = new MyBaseAdapter(historyList);
                    history_listView.setAdapter(mAdapter);
                }else{
                    mAdapter.notifyDataSetChanged();
                }
            }else {
                historyList.clear();
				for (int i =0;i<list.size();i++){
					historyList.add(list.get(i).getSearchStr());
				}
                if(mAdapter == null){
                    mAdapter = new MyBaseAdapter(historyList);
                    history_listView.setAdapter(mAdapter);
                }else{
                    mAdapter.notifyDataSetChanged();
                }
            }
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(historyList != null && historyList.size() > 0){
			ll_historyListView.setVisibility(View.VISIBLE);
			hotLayout.setVisibility(View.GONE);
		}else{
			ll_historyListView.setVisibility(View.GONE);
			hotLayout.setVisibility(View.VISIBLE);
		}

	}

	/************** 操作数据库 ***********/
	/**
	 * 检查数据库中是否已经有该条记录
	 */
	public boolean hasData(String tempName) {
		if(TextUtils.isEmpty(tempName)){
			return false;
		}
		try {
			SearchHistoryGD unique = GDManager.getInstance().getSession().getSearchHistoryGDDao().queryBuilder().where(SearchHistoryGDDao.Properties.SearchStr.eq(tempName)).unique();
			if(unique!=null&&!TextUtils.isEmpty(unique.getSearchStr())) {
                return true;
            }
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 检查表内是否有数据
	 */
	public  int hastableData(String tempName) {

		List<SearchHistoryGD> list = null;
		try {
			list = GDManager.getInstance().getSession().getSearchHistoryGDDao().queryBuilder().where(SearchHistoryGDDao.Properties.SearchStr.eq(tempName)).build().list();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list.size();
	}

	/**
	 * 清空数据
	 */
	private void deleteData() {
		try {
			GDManager.getInstance().getSession().getSearchHistoryGDDao().deleteAll();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 删除某一条数据
	 */
	private void deletehistoryData(String temp) {
		try {
			SearchHistoryGD unique = GDManager.getInstance().getSession().getSearchHistoryGDDao().queryBuilder().where(SearchHistoryGDDao.Properties.SearchStr.eq(temp)).unique();
			if(unique!=null) {
                GDManager.getInstance().getSession().getSearchHistoryGDDao().delete(unique);
            }
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		//当滑动停止并且滑动到底部时加载更多数据
		if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
			if (view.getLastVisiblePosition() >= (view.getCount() - 2)) {
				if(!isRefreshing){
					page++;
					searchData(editText.getText().toString(),false);
				}
			}
		}
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

	}

	//	搜索历史适配器
	class MyBaseAdapter extends BaseAdapter implements OnClickListener {

		List<String> hList;

		public MyBaseAdapter(List<String> historyList) {
			hList =historyList;
		}

		@Override
		public int getCount() {
			return hList.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			ViewHolder holder ;
			if(convertView==null) {
			    holder = new ViewHolder();
				convertView = View.inflate(SearchActivity.this, R.layout.item_search_historylist, null);
				holder.it_textview = (TextView) convertView.findViewById(R.id.it_textview);
				holder.it_imageview = convertView.findViewById(R.id.it_imageview);
				convertView.setTag(holder);
			}else {
				holder = (ViewHolder) convertView.getTag();
			}

			holder.it_textview.setText(hList.get(position));
			holder.it_imageview.setTag(hList.get(position));
			holder.it_imageview.setOnClickListener(this);
			return convertView;
		}

		@Override
		public void onClick(View v) {
			if(v == null){
				return;
			}
			String str = v.getTag().toString();
			deletehistoryData(str);
			queryData("");
		}
	}
	
	

	class ViewHolder {
		TextView it_textview;
		View it_imageview;
	}

	/************** 操作数据库 ***********/
}
